package service.impl;

import common.impl.exception.ServiceException;

import model.MWriting;
import net.sf.json.JSONObject;
import service.interf.IWriting;
import dao.interf.IWritingDao;
import dao.pojo.Writing;

public class WritingImpl implements IWriting{
	private IWritingDao writingDao;

	public void setWritingDao(IWritingDao writingDao) {
		this.writingDao = writingDao;
	}

	@Override
	public String add(MWriting model) {
		Writing writing = new Writing();
		writing.setWriteContent(model.getWriteContent());
		writing.setWriteDriection(model.getWriteDriection());
		writing.setWriteUrl(model.getWriteUrl());
		return writingDao.add(writing);
	}

	@Override
	public String getById(MWriting model) {
		Writing writing = writingDao.getById(model.getWriteId());
		if(null == writing) {
			throw new ServiceException("ERR-0101");
		}
		return createWritingObj(writing).toString();
	}

	@Override
	public String deleteById(Integer id) {
		writingDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MWriting model) {
		Writing writing = writingDao.getById(model.getWriteId());
		if (null == writing) {
			throw new ServiceException("ERR-0101");
		}
		writing.setWriteContent(model.getWriteContent());
		writing.setWriteDriection(model.getWriteDriection());
		writing.setWriteUrl(model.getWriteUrl());
		writingDao.edit(writing);
		return "1";
	}

	public JSONObject createWritingObj(Writing writing) {
		JSONObject obj = new JSONObject();

		obj.put("writeId", writing.getWriteId());
		obj.put("writeDriection", writing.getWriteDriection());
		obj.put("writeContent", writing.getWriteContent());
		obj.put("writeUrl", writing.getWriteUrl());

		return obj;
	}

}
